/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.pomty.pombook;

import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.codecarpet.fbconnect.FBRequest;
import com.codecarpet.fbconnect.FBSession;
import com.codecarpet.fbconnect.FBRequest.FBRequestDelegate;
import com.pomty.pombook.gallery.IImage;

public class FBImageGallery extends ImageGallery {
	private static final String ALBUMNAME = "albumName";
    private static final String ALBUMID = "albumId";
	private ProgressDialog mProgress;
	volatile boolean mAbort = false;
	
	private String mAlbumId;
	private String mAlbumName;
	
	@Override
    public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
        mProgress = new ProgressDialog(this);
        mProgress = new ProgressDialog(this);
		mProgress.setTitle(R.string.loadPhotosDialogTitle);
		mProgress.setOnCancelListener(new OnCancelListener() {
			
			@Override
			public void onCancel(DialogInterface dialog) {
				mAbort = true;
			}
		});
		Intent intent = getIntent();
		
		if (icicle != null) {
			mAlbumId = icicle.getString(ALBUMID);
    		mAlbumName = icicle.getString(ALBUMNAME);
        } else {
    		Bundle extras = intent.getExtras();
    		mAlbumName = (String)extras.get("windowTitle");
        }
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mAbort = true;
	}

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
		
		if (FBSession.getSession() != null && FBSession.getSession().isConnected())
		{
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.menu_refresh_pics, menu);
		}
		
        return true;
    }

	
	@Override
    protected MenuItem addSlideShowMenu(Menu menu) {
        return menu.add(Menu.NONE, Menu.NONE, MenuHelper.POSITION_SLIDESHOW,
                R.string.slide_show)
                .setOnMenuItemClickListener(
                new MenuItem.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {
                    	return onSlideShowClicked();
                    }
                }).setIcon(android.R.drawable.ic_menu_slideshow);
    }

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case R.id.itemRefreshPics:
			mAbort = false;
			updatePics();
	    	return true;
		}
		return false;
	}
	
	@Override
	protected void rebake(boolean unmounted, boolean scanning) {
		rebake(unmounted, scanning, true);
	}
	
	protected void rebake(boolean unmounted, boolean scanning, boolean updatePicsIfNeeded) {
		mGvs.stop();
        if (mAllImages != null) {
            mAllImages.close();
            mAllImages = null;
        }

        if (mMediaScanningDialog != null) {
            mMediaScanningDialog.cancel();
            mMediaScanningDialog = null;
        }

        if (scanning) {
            mMediaScanningDialog = ProgressDialog.show(
                    this,
                    null,
                    getResources().getString(R.string.wait),
                    true,
                    true);
        }

        mParam = allImages(!unmounted && !scanning);
        mAllImages = ImageManager.makeImageList(getContentResolver(), mParam);
        mAllImages.open(getContentResolver());
        mGvs.setImageList(mAllImages);
        mGvs.setDrawAdapter(this);
        mGvs.setLoader(mLoader);
        mGvs.start();
        mNoImagesView.setVisibility(mAllImages.getCount() > 0
                ? View.GONE
                : View.VISIBLE);
        if (updatePicsIfNeeded && mAllImages.getCount() < 2)
        {
        	updatePics();
        }

	}
	
	
	
	private void updatePics()
	{
    	Thread worker = new Thread(new Runnable() {
    		public void run() {
    			if (mAbort)
    				return;
    			
    			mHandler.post(new Runnable() {
    				public void run() {
    					mProgress.setMessage(getString(R.string.loadPhotosDialogMessage));
    					mProgress.show();
      				}});
    			
    			
    			DBHelper dbHelper = new DBHelper(getApplicationContext());
    	    	SQLiteDatabase db = dbHelper.getReadableDatabase();
    	    	Cursor cursor = db.query(DBHelper.TABLEALBUM, new String[] {"AID", "NAME"},    			
    	                null, null, null, null, null);
    	    	
	    		startManagingCursor(cursor);
    	    	int indexAid = cursor.getColumnIndex("AID");
    	    	if (cursor != null && cursor.getCount() != 0)
    	    	{
    	    		while (cursor.moveToNext())
    	    		{
    	    			if (mAlbumName.equals(Util.folderNameFromString(cursor.getString(1))))
    	    			{
    	    				mAlbumId = cursor.getString(indexAid);
    	    				break;
    	    			}
    	    		}
        	    }
    	    	db.close();
    	    	cursor.close();
    			
    			
    			FBRequest _photoRequest = FBRequest.requestWithDelegate(new FBRequestPhotoDelegateImpl2());
                Map<String, String> parameters = new HashMap<String, String>();
            	parameters.put("aid", mAlbumId);
            	_photoRequest.call("Photos.get", parameters);
             }
        });
    	worker.start();
		
	}
	
    private class FBRequestPhotoDelegateImpl2 extends FBRequestDelegate {
    	@Override
		public void requestDidLoad(FBRequest request, Object result) {
			if (!(result instanceof JSONArray))
			{
	        	mHandler.post(new Runnable() {
					public void run() {
						mProgress.hide();
						rebake(false, false, false);
	  				}});
	        	return;
			}
			
			JSONArray resultPhotoRequest = (JSONArray)result;
			
			HashMap<String, Object> map = new HashMap<String, Object>();
        	DBHelper dbHelper = new DBHelper(getApplicationContext());
        	SQLiteDatabase db = dbHelper.getWritableDatabase();
        	ContentValues values = new ContentValues();
        	final int nbPics  = resultPhotoRequest.length();
        	JSONObject o;
        	Iterator ji;
        	String key;
        	Object val;
        	Cursor cursor;
        	String currentCoverId;
        	for (int i = 0; i < nbPics; i++)
			{
    			if (mAbort)
    			{
    				mHandler.post(new Runnable() {
						
						@Override
						public void run() {
							rebake(false, false, false);
						}
					});
    				break;
    			}
    			
        		final int index = i + 1;
				
    			mHandler.post(new Runnable() {
    				public void run() {
    					mProgress.setMessage(getString(R.string.loadPhotosDialogMessage) + " " + index + "/" + nbPics);
      				}});
        		map.clear();
        		try {
					o = (JSONObject) resultPhotoRequest.get(i);
					ji = o.keys();
					while (ji.hasNext()) {
						key = (String) ji.next();
					    val = o.get(key);
				        map.put(key, val);
					}
					       
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (map.containsKey("pid") && map.containsKey("src_big"))
				{
					currentCoverId = (String)map.get("pid");
				
	                cursor = db.query("PHOTO", new String[] {"ID", "PID"}, 
		                    "PID = '" + currentCoverId + "'", null, null, null, null);
	
		        	startManagingCursor(cursor);
		        	
		        	if (cursor.getCount() == 0)
		        	{			            
			        	try{
	                		final URL fileUrl = new URL ((String)map.get("src_big"));
	                		//item = new GridPhotoItem(currentCoverId, mAlbumName, getApplicationContext());

	                		File file = Util.createFile(fileUrl, currentCoverId, mAlbumName, true);
	                		
	                		// When the last photo is added we reload the view
	                		if (i == nbPics - 1)
                			{
	                			new MediaScannerNotifier(getApplicationContext(), file.getAbsolutePath(), null, new Runnable() {
                					
									@Override
									public void run() {
										mHandler.post(new Runnable() {
											
											@Override
											public void run() {
												rebake(false, false, false);
											}
										});
									}
								}); 
                			}
	                		else
	                			new MediaScannerNotifier(getApplicationContext(), file.getAbsolutePath(), null);
	                		
			        		//values.put("URL", (String)map.get("src"));
			        		//values.put("URLBIG", (String)map.get("src_big"));
			        		//values.put("URLSMALL", (String)map.get("src_small"));
			        		//values.put("LINK", (String)map.get("link"));
			        		//values.put("CAPTION", (String)map.get("caption"));
			        		values.put("AID", (String)map.get("aid"));
				        	values.put("PID", currentCoverId);
				        	db.insert("PHOTO", "CAPTION", values);
	                	}
	                	catch (Exception e)
	                	{
	                		e.printStackTrace();
	                	}
		        	}
	        		cursor.close();
				}
	        }
        	mHandler.post(new Runnable() {
				public void run() {
					mProgress.hide();					
	    		}});
        }

		@Override
		public void requestDidFailWithError(FBRequest request,
				Throwable error) {
			mHandler.post(new Runnable() {
				public void run() {
					mProgress.hide();
					Toast.makeText(getApplicationContext(), R.string.error, Toast.LENGTH_LONG).show();
  				}});
			super.requestDidFailWithError(request, error);
		}

		@Override
		public void requestWasCancelled(FBRequest request) {
			mHandler.post(new Runnable() {
				public void run() {
					mProgress.hide();
					Toast.makeText(getApplicationContext(), R.string.error, Toast.LENGTH_LONG).show();
  				}});
			super.requestWasCancelled(request);
		}
    }
    
    @Override
    public void onImageClicked(int index) {
        if (index < 0 || index >= mAllImages.getCount()) {
            return;
        }
        mSelectedIndex = index;
        mGvs.setSelectedIndex(index);

        IImage image = mAllImages.getImageAt(index);

        Intent intent;

        intent = new Intent(this, ViewImage.class);
        intent.putExtra(ViewImage.KEY_IMAGE_LIST, mParam);
        intent.setData(image.fullSizeImageUri());
        
        startActivity(intent);
    }
	
	

    
}
